package com.example.sqlitetest;

import androidx.appcompat.app.AppCompatActivity;

import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import java.text.SimpleDateFormat;

public class MainActivity extends AppCompatActivity {
    SQLiteDatabase db;
    Button bn = null;
    ListView listview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString() + "/my.db3",null);
        listview = findViewById(R.id.ltv);
        bn = findViewById(R.id.button);
        bn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String title = ((EditText) findViewById(R.id.et1)).getText().toString();
                String content = ((EditText) findViewById(R.id.et2)).getText().toString();
                try {
                    insertData(db, title, content);
                    Cursor cursor = db.rawQuery("select * from news_inf", null);
                    inflateList(cursor);
                } catch (SQLException se) {
                    db.execSQL("create table news_inf(_id integer" +
                            " primary key autoincrement," +
                            "news_title varchar(50)," +
                            "news_content varcahr(255))");
                    insertData(db, title, content);
                    Cursor cursor = db.rawQuery("select * from news_inf", null);
                    inflateList(cursor);

                }
            }

        });
    }
    private void insertData(SQLiteDatabase db,String title,String content){
        db.execSQL("insert into news_inf values(null,?,?)",
                new String[] {title,content });
    }
    private void inflateList(Cursor cursor){
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(
                MainActivity.this,R.layout.line,cursor,
                new String[] {"news_title","news_content"},
                new int[] {R.id.my_title,R.id.my_content},
                CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        listview.setAdapter(adapter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (db != null && db.isOpen()){
            db.close();
        }
    }
}
